<?php
session_start();
require_once '../includes/config.php';
require_once '../includes/database.php';
require_once '../includes/auth.php';
require_once '../includes/report_manager.php';

// 检查权限
$auth = getAuth();
$auth->requirePermission('super_admin');

// 获取当前用户信息
$currentUser = $auth->getCurrentUser();

// 初始化数据库和报表管理器
$database = getDatabaseConnection();
$reportManager = new ReportManager($database);

// 获取查询参数
$reportType = $_GET['report_type'] ?? 'monthly';
$year = $_GET['year'] ?? date('Y');
$month = $_GET['month'] ?? date('m');
$startDate = $_GET['start_date'] ?? date('Y-m-01');
$endDate = $_GET['end_date'] ?? date('Y-m-t');

// 获取可用的月份
$availableMonths = $reportManager->getAvailableMonths();

// 根据报表类型获取数据
$reportData = [];
$summaryData = [];

switch ($reportType) {
    case 'monthly':
        $reportData = $reportManager->getMonthlyAttendanceReport($year, $month);
        $summaryData = $reportManager->getAttendanceSummary("{$year}-{$month}-01", date('Y-m-t', strtotime("{$year}-{$month}-01")));
        break;
    case 'department':
        $reportData = $reportManager->getDepartmentAttendanceReport($startDate, $endDate);
        $summaryData = $reportManager->getAttendanceSummary($startDate, $endDate);
        break;
    case 'exception':
        $reportData = $reportManager->getAttendanceExceptionReport($startDate, $endDate);
        $summaryData = $reportManager->getAttendanceSummary($startDate, $endDate);
        break;
    case 'overtime':
        $reportData = $reportManager->getOvertimeReport($startDate, $endDate);
        $summaryData = $reportManager->getAttendanceSummary($startDate, $endDate);
        break;
    case 'trend':
        $reportData = $reportManager->getAttendanceTrend($startDate, $endDate);
        $summaryData = $reportManager->getAttendanceSummary($startDate, $endDate);
        break;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>统计报表 - 考勤管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- 侧边栏 -->
    <?php include_once '../includes/sidebar.php'; ?>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand navbar-custom mb-4">
            <div class="container-fluid">
                <div class="navbar-nav me-auto">
                    <span class="navbar-text">
                        <i class="fas fa-chart-bar me-2"></i>统计报表
                    </span>
                </div>
                <div class="navbar-nav">
                    <span class="navbar-text me-3">
                        <i class="fas fa-user me-2"></i>
                        <?php echo htmlspecialchars($currentUser['full_name']); ?>
                    </span>
                    <a href="../user/profile.php" class="nav-link">
                        <i class="fas fa-cog"></i> 个人设置
                    </a>
                </div>
            </div>
        </nav>

        <!-- 报表类型选择 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-filter me-2"></i>报表筛选
                </h5>
            </div>
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">报表类型</label>
                        <select name="report_type" class="form-select" onchange="this.form.submit()">
                            <option value="monthly" <?php echo $reportType === 'monthly' ? 'selected' : ''; ?>>月度考勤报表</option>
                            <option value="department" <?php echo $reportType === 'department' ? 'selected' : ''; ?>>部门统计</option>
                            <option value="exception" <?php echo $reportType === 'exception' ? 'selected' : ''; ?>>异常考勤</option>
                            <option value="overtime" <?php echo $reportType === 'overtime' ? 'selected' : ''; ?>>加班统计</option>
                            <option value="trend" <?php echo $reportType === 'trend' ? 'selected' : ''; ?>>考勤趋势</option>
                        </select>
                    </div>
                    
                    <?php if ($reportType === 'monthly'): ?>
                        <div class="col-md-3">
                            <label class="form-label">年份</label>
                            <select name="year" class="form-select">
                                <?php for ($y = date('Y'); $y >= 2020; $y--): ?>
                                    <option value="<?php echo $y; ?>" <?php echo $year == $y ? 'selected' : ''; ?>><?php echo $y; ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">月份</label>
                            <select name="month" class="form-select">
                                <?php for ($m = 1; $m <= 12; $m++): ?>
                                    <option value="<?php echo sprintf('%02d', $m); ?>" <?php echo $month == sprintf('%02d', $m) ? 'selected' : ''; ?>>
                                        <?php echo $m; ?>月
                                    </option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    <?php else: ?>
                        <div class="col-md-3">
                            <label class="form-label">开始日期</label>
                            <input type="date" name="start_date" class="form-control" value="<?php echo $startDate; ?>">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">结束日期</label>
                            <input type="date" name="end_date" class="form-control" value="<?php echo $endDate; ?>">
                        </div>
                    <?php endif; ?>
                    
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">生成报表</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 汇总统计 -->
        <?php if (!empty($summaryData)): ?>
            <div class="row mb-4">
                <div class="col-md-2">
                    <div class="card bg-primary text-white">
                        <div class="card-body text-center">
                            <h4><?php echo $summaryData['total_users'] ?? 0; ?></h4>
                            <p class="mb-0">参与人数</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-success text-white">
                        <div class="card-body text-center">
                            <h4><?php echo $summaryData['normal_count'] ?? 0; ?></h4>
                            <p class="mb-0">正常</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-warning text-white">
                        <div class="card-body text-center">
                            <h4><?php echo $summaryData['late_count'] ?? 0; ?></h4>
                            <p class="mb-0">迟到</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-danger text-white">
                        <div class="card-body text-center">
                            <h4><?php echo $summaryData['early_leave_count'] ?? 0; ?></h4>
                            <p class="mb-0">早退</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-secondary text-white">
                        <div class="card-body text-center">
                            <h4><?php echo $summaryData['absent_count'] ?? 0; ?></h4>
                            <p class="mb-0">缺勤</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-2">
                    <div class="card bg-info text-white">
                        <div class="card-body text-center">
                            <h4><?php echo number_format($summaryData['avg_work_hours'] ?? 0, 1); ?></h4>
                            <p class="mb-0">平均工时</p>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <!-- 报表内容 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-chart-bar me-2"></i>
                    <?php
                    $reportTitles = [
                        'monthly' => '月度考勤报表',
                        'department' => '部门考勤统计',
                        'exception' => '异常考勤记录',
                        'overtime' => '加班统计报表',
                        'trend' => '考勤趋势分析'
                    ];
                    echo $reportTitles[$reportType] ?? '统计报表';
                    ?>
                </h5>
                <div>
                    <button class="btn btn-success btn-sm" onclick="exportReport()">
                        <i class="fas fa-download me-2"></i>导出报表
                    </button>
                </div>
            </div>
            <div class="card-body">
                <?php if (empty($reportData)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-chart-bar fa-4x mb-3"></i>
                        <h4>暂无数据</h4>
                        <p>当前筛选条件下没有找到相关数据</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="reportTable">
                            <thead>
                                <?php if ($reportType === 'monthly'): ?>
                                    <tr>
                                        <th>姓名</th>
                                        <th>部门</th>
                                        <th>职位</th>
                                        <th>总天数</th>
                                        <th>正常</th>
                                        <th>迟到</th>
                                        <th>早退</th>
                                        <th>缺勤</th>
                                        <th>请假</th>
                                        <th>出差</th>
                                        <th>总工时</th>
                                        <th>平均工时</th>
                                    </tr>
                                <?php elseif ($reportType === 'department'): ?>
                                    <tr>
                                        <th>部门</th>
                                        <th>总记录</th>
                                        <th>正常</th>
                                        <th>迟到</th>
                                        <th>早退</th>
                                        <th>缺勤</th>
                                        <th>请假</th>
                                        <th>出差</th>
                                        <th>总工时</th>
                                        <th>平均工时</th>
                                    </tr>
                                <?php elseif ($reportType === 'exception'): ?>
                                    <tr>
                                        <th>姓名</th>
                                        <th>部门</th>
                                        <th>职位</th>
                                        <th>日期</th>
                                        <th>上班时间</th>
                                        <th>下班时间</th>
                                        <th>工作时长</th>
                                        <th>状态</th>
                                        <th>备注</th>
                                    </tr>
                                <?php elseif ($reportType === 'overtime'): ?>
                                    <tr>
                                        <th>姓名</th>
                                        <th>部门</th>
                                        <th>职位</th>
                                        <th>日期</th>
                                        <th>工作时长</th>
                                        <th>加班时长</th>
                                    </tr>
                                <?php elseif ($reportType === 'trend'): ?>
                                    <tr>
                                        <th>日期</th>
                                        <th>总记录</th>
                                        <th>正常</th>
                                        <th>迟到</th>
                                        <th>早退</th>
                                        <th>缺勤</th>
                                        <th>平均工时</th>
                                    </tr>
                                <?php endif; ?>
                            </thead>
                            <tbody>
                                <?php foreach ($reportData as $row): ?>
                                    <tr>
                                        <?php if ($reportType === 'monthly'): ?>
                                            <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                            <td><?php echo htmlspecialchars($row['department']); ?></td>
                                            <td><?php echo htmlspecialchars($row['position']); ?></td>
                                            <td><?php echo $row['total_days']; ?></td>
                                            <td><?php echo $row['normal_days']; ?></td>
                                            <td><?php echo $row['late_days']; ?></td>
                                            <td><?php echo $row['early_leave_days']; ?></td>
                                            <td><?php echo $row['absent_days']; ?></td>
                                            <td><?php echo $row['leave_days']; ?></td>
                                            <td><?php echo $row['business_trip_days']; ?></td>
                                            <td><?php echo number_format($row['total_work_hours'], 1); ?></td>
                                            <td><?php echo number_format($row['avg_work_hours'], 1); ?></td>
                                        <?php elseif ($reportType === 'department'): ?>
                                            <td><?php echo htmlspecialchars($row['department']); ?></td>
                                            <td><?php echo $row['total_records']; ?></td>
                                            <td><?php echo $row['normal_count']; ?></td>
                                            <td><?php echo $row['late_count']; ?></td>
                                            <td><?php echo $row['early_leave_count']; ?></td>
                                            <td><?php echo $row['absent_count']; ?></td>
                                            <td><?php echo $row['leave_count']; ?></td>
                                            <td><?php echo $row['business_trip_count']; ?></td>
                                            <td><?php echo number_format($row['total_work_hours'], 1); ?></td>
                                            <td><?php echo number_format($row['avg_work_hours'], 1); ?></td>
                                        <?php elseif ($reportType === 'exception'): ?>
                                            <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                            <td><?php echo htmlspecialchars($row['department']); ?></td>
                                            <td><?php echo htmlspecialchars($row['position']); ?></td>
                                            <td><?php echo $row['record_date']; ?></td>
                                            <td><?php echo $row['clock_in'] ?: '-'; ?></td>
                                            <td><?php echo $row['clock_out'] ?: '-'; ?></td>
                                            <td><?php echo number_format($row['work_hours'], 1); ?></td>
                                            <td>
                                                <?php
                                                $statusLabels = [
                                                    'late' => '迟到',
                                                    'early_leave' => '早退',
                                                    'absent' => '缺勤'
                                                ];
                                                echo $statusLabels[$row['status']] ?? $row['status'];
                                                ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($row['notes'] ?: '-'); ?></td>
                                        <?php elseif ($reportType === 'overtime'): ?>
                                            <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                            <td><?php echo htmlspecialchars($row['department']); ?></td>
                                            <td><?php echo htmlspecialchars($row['position']); ?></td>
                                            <td><?php echo $row['record_date']; ?></td>
                                            <td><?php echo number_format($row['work_hours'], 1); ?></td>
                                            <td><?php echo number_format($row['overtime_hours'], 1); ?></td>
                                        <?php elseif ($reportType === 'trend'): ?>
                                            <td><?php echo $row['date']; ?></td>
                                            <td><?php echo $row['total_records']; ?></td>
                                            <td><?php echo $row['normal_count']; ?></td>
                                            <td><?php echo $row['late_count']; ?></td>
                                            <td><?php echo $row['early_leave_count']; ?></td>
                                            <td><?php echo $row['absent_count']; ?></td>
                                            <td><?php echo number_format($row['avg_work_hours'], 1); ?></td>
                                        <?php endif; ?>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script>
        // 导出报表功能
        function exportReport() {
            const table = document.getElementById('reportTable');
            const wb = XLSX.utils.table_to_book(table, {sheet: "报表"});
            
            // 生成文件名
            const reportType = '<?php echo $reportType; ?>';
            const reportTitles = {
                'monthly': '月度考勤报表',
                'department': '部门考勤统计',
                'exception': '异常考勤记录',
                'overtime': '加班统计报表',
                'trend': '考勤趋势分析'
            };
            
            let fileName = reportTitles[reportType] || '统计报表';
            
            <?php if ($reportType === 'monthly'): ?>
                fileName += `_<?php echo $year; ?>年<?php echo $month; ?>月`;
            <?php else: ?>
                fileName += `_<?php echo $startDate; ?>_至_<?php echo $endDate; ?>`;
            <?php endif; ?>
            
            fileName += '.xlsx';
            
            XLSX.writeFile(wb, fileName);
        }

        // 页面加载完成后的一些初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置默认日期范围
            const startDateInput = document.querySelector('input[name="start_date"]');
            const endDateInput = document.querySelector('input[name="end_date"]');
            
            if (startDateInput && endDateInput) {
                // 如果日期为空，设置默认值
                if (!startDateInput.value) {
                    startDateInput.value = '<?php echo date('Y-m-01'); ?>';
                }
                if (!endDateInput.value) {
                    endDateInput.value = '<?php echo date('Y-m-t'); ?>';
                }
            }
        });
    </script>
</body>
</html>
